package VIEWS;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import CONTROLLERS.HoSoBAControllers;
import CONTROLLERS.UsersControllers;
import ModelEntityFW.BenhNhanEntity;
import ModelEntityFW.HosoBAEntity;
import ModelEntityFW.UserEntitys;
import Ultils.Controls;
import Ultils.FileIOStreams;

import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.JFileChooser;

import java.awt.Font;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.Vector;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class HoSoBA extends JFrame {

	private JPanel contentPane;
	private static Connection m_objConnection;
    private HoSoBAControllers m_objHOSOBAController;
    private static UserEntitys m_objSecurityContext;
    private DefaultTableModel objDTM;
    private static boolean bFlag = false;
    private HosoBAEntity m_objHSBAEntity;
    private JTable table;
    
	/**
	 * Launch the application.
	 */
	/*public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					HoSoBA frame = new HoSoBA();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}*/

	/**
	 * Create the frame.
	 */
	public HoSoBA(Connection objConnection, UserEntitys objSecurity) {
		m_objConnection=objConnection;
		m_objSecurityContext=objSecurity;
		m_objHSBAEntity = new HosoBAEntity();
	    objDTM=new DefaultTableModel();
		
		setTitle("---QUẢN LÝ HỒ SƠ BỆNH ÁN---");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 838, 421);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JToolBar toolBar = new JToolBar();
		toolBar.setBounds(0, 0, 822, 46);
		contentPane.add(toolBar);
		
		JButton btnNewButton = new JButton("Thêm Hồ Sơ BA[+]");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

                HosoBAEntity objHSBAEn = new HosoBAEntity();
                UUID objGui = UUID.randomUUID();
                objHSBAEn.setHoSoID(objGui.compareTo(objGui));

                objHSBAEn.setbFlag(false);
                HoSoBAAdd HSBAAdd = new HoSoBAAdd(m_objConnection, m_objSecurityContext, objHSBAEn);
                HSBAAdd.setLocation(400, 200);
                HSBAAdd.setVisible(true);
                //dispose();
			}
		});
		btnNewButton.setIcon(new ImageIcon(HoSoBA.class.getResource("/images/book_edit.png")));
		btnNewButton.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(btnNewButton);
		
		JButton btnCpNht = new JButton("Cập nhật[!]");
		btnCpNht.setIcon(new ImageIcon(HoSoBA.class.getResource("/images/editgv2.png")));
		btnCpNht.setFont(new Font("Cambria", Font.PLAIN, 14));
		btnCpNht.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(bFlag){
					Vector<String> lisItem = HoSoBAAdd.getItemBNID(m_objConnection);
					
					m_objHSBAEntity.setbFlag(bFlag);
					m_objHSBAEntity.setHoSoID(Integer.parseInt(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 0))));
					m_objHSBAEntity.setNgayTaoHS(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 1)));
					m_objHSBAEntity.setNguoiTaoHS(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 2)));
					m_objHSBAEntity.setBHYT(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 3)).equals("Có") ? 0:1);
					m_objHSBAEntity.setBHXH(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 4)).equals("Có") ? 0:1);
					String temp = String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 5));
					for (String string : lisItem) {
						if(temp.equals(string)){
							m_objHSBAEntity.setBN_ID(lisItem.indexOf(string));
							break;
						}
					}
					
					HoSoBAAdd frm = new HoSoBAAdd(m_objConnection, m_objSecurityContext, m_objHSBAEntity);
					frm.setVisible(true);
					
					bFlag = false;
				}else{
					JOptionPane.showMessageDialog(getParent(), "Bạn cần chọn thông tin cập nhật!!!");
				}
			}
		});
		toolBar.add(btnCpNht);
		
		JButton btnXa = new JButton("Xóa[-]");
		btnXa.setIcon(new ImageIcon(HoSoBA.class.getResource("/images/6_3.png")));
		btnXa.setFont(new Font("Cambria", Font.PLAIN, 14));
		btnXa.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
                int opt = JOptionPane.showConfirmDialog(getParent(), "Bạn có chắc chắn muốn xóa dữ liệu này?",
                        "Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null);
                if (opt == 0) {
                    // Yes
                    int getId = Integer.parseInt(String.valueOf(objDTM.getValueAt(table.getSelectedRow(), 0)));

                    boolean bResult = false;
                    try {
                        HosoBAEntity objEntity = new HosoBAEntity();
                        objEntity.setHoSoID(getId);
                        bResult = m_objHOSOBAController.ExecOfDeleteElement(objEntity);
                    } catch (Exception e1) {
                        JOptionPane.showMessageDialog(getParent(), "Lỗi xóa thông tin người dùng!", "Thông báo",
                                JOptionPane.ERROR_MESSAGE);
                    }

                    if (bResult) {
                        JOptionPane.showMessageDialog(getParent(), "Xóa tài khoản thành công!", "Thông báo",
                                JOptionPane.ERROR_MESSAGE);

                        // Thực thi hiển thị dữ liệu
                        LoadData(true);
                    } else {
                        JOptionPane.showMessageDialog(getParent(), "Xóa tài khoản thất bại!", "Thông báo",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
			}
		});
		toolBar.add(btnXa);
		
		JButton btnTmKim = new JButton("Tìm Kiếm[=]");
		btnTmKim.setIcon(new ImageIcon(HoSoBA.class.getResource("/images/search.png")));
		btnTmKim.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(btnTmKim);
		
		JButton btnLmMi = new JButton("Làm mới[^]");
		btnLmMi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				LoadData(true);
			}
		});
		btnLmMi.setIcon(new ImageIcon(HoSoBA.class.getResource("/images/renew.png")));
		btnLmMi.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(btnLmMi);
		
		JButton btnGhiXungFile = new JButton("Ghi xuống file[*]");
		btnGhiXungFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object[] options = { "XML File", "JSON File", "Hủy bỏ" };
                int n = JOptionPane.showOptionDialog(getParent(), "Hãy chọn loại File bạn muốn ghi: ",
                        "Chọn thể lại File", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        options, options[1]);
                if (n == 0) {

                	List<Object> LisField = new ArrayList<Object>();
                	List<List<Object>> LisValues = new ArrayList<List<Object>>();
                	List<Object> Values = new ArrayList<Object>();
                	ResultSet objRs = null;
                	ResultSetMetaData objMdata = null;
                	try {
						objRs = m_objHOSOBAController.ExecOfGetElements();
						objMdata = objRs.getMetaData();
			
						int col = objMdata.getColumnCount();
						
						for(int i=1;i<=col;i++){
							LisField.add(objMdata.getColumnName(i));
						}
						while(objRs.next()){
							Values = new ArrayList<Object>();
							for(int j=1;j<=col;j++){
								Values.add(objRs.getString(j));
							}
							LisValues.add(Values);
						}
							boolean bResult=false;
		                JFileChooser objFile = new JFileChooser();
		                objFile.setCurrentDirectory(new java.io.File("."));
		                objFile.setDialogTitle("Chọn file: ");
		                objFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		                String[] EXTENSION = new String[] { "xml" };
		                FileNameExtensionFilter filter = new FileNameExtensionFilter("XML files", EXTENSION);
		                objFile.setFileFilter(filter);
		                objFile.setMultiSelectionEnabled(false);

		                int returnVal = objFile.showSaveDialog(getParent());
		                String ParentPath = "";
		                String FileName = "";
		                if (returnVal == JFileChooser.APPROVE_OPTION) {
		                    ParentPath = objFile.getSelectedFile().getParent();
		                    FileName = objFile.getSelectedFile().getName();
		                    
		                    String path = ParentPath+"/"+FileName+".xml";
		                    FileIOStreams<BenhNhanEntity> objFileIO = new FileIOStreams<BenhNhanEntity>();
		                    try {
								bResult= objFileIO.WriteElements(LisField, LisValues, "PMQUANLYBENHVIEN", "HOSOBA", path, true);
								
							} catch (Exception e1) {
								// TODO: handle exception
								JOptionPane.showMessageDialog(getParent(), "Err:"+e1.getMessage());
							}
		                    if(bResult){
		                    	JOptionPane.showMessageDialog(getParent(), "Ghi xuống File XML thành công", "THÔNG BÁO", JOptionPane.INFORMATION_MESSAGE);
		                    }
		                }
		            
					} catch (Exception e1) {
						
					}
                    
                
                    JOptionPane.showMessageDialog(getParent(), "Ghi XML thành công!");
                } else if (n == 1) {
                    JOptionPane.showMessageDialog(getParent(), "Ghi JSon thành công!");
                }
			}
		});
		btnGhiXungFile.setIcon(new ImageIcon(HoSoBA.class.getResource("/images/save.png")));
		btnGhiXungFile.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(btnGhiXungFile);
		
		JButton btnThot = new JButton("Thoát[x]");
		btnThot.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		btnThot.setIcon(new ImageIcon(HoSoBA.class.getResource("/images/cancel.gif")));
		btnThot.setFont(new Font("Cambria", Font.PLAIN, 14));
		toolBar.add(btnThot);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(0, 57, 822, 301);
		contentPane.add(scrollPane);
		
		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				bFlag = true;
			}
		});
		table.setFillsViewportHeight(true);
		table.setColumnSelectionAllowed(true);
		table.setCellSelectionEnabled(true);
		scrollPane.setViewportView(table);
		LoadData(true);
	}
	
	public void LoadData(boolean typeData) {
        try {
            // 1. Kiểm tra trạng thái kết nối
            if (!m_objConnection.isClosed()) {
                ResultSet objRS = null;
                if (typeData) {
                    // 2. Thực thi nhận v�? tập bản ghi Users
                    if (m_objHOSOBAController == null) {
                        m_objHOSOBAController = new HoSoBAControllers(m_objConnection, m_objSecurityContext);
                    }
                    try {
                        objRS = m_objHOSOBAController.ExecOfGetElements();
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(getParent(), "Err: " + e, "Thông báo", JOptionPane.ERROR_MESSAGE);
                    }
                }
                // 3. Khai báo khởi tạo đối tượng
                Controls objControls = new Controls();

                // 4. Thực thi phương thức getModels để nhận v�?
                // DefaulTableModels
                try {
                    objDTM = objControls.getModels(objRS);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                table.setModel(objDTM);

                
            } else {
                JOptionPane.showMessageDialog(getParent(), "Không kết nối được với CSDL!", "Thông báo",
                        JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(getParent(), "Có lỗi xảy ra. Chi tiết: " + ex.getMessage(), "Thông báo",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}
